<template>
  <div>
    <div style="bottom: 74px;top: 100px;position: fixed;">
      <div class="user_seal_apply">
        <van-form ref="form" :model="form"  >

          <div class="table_div" >
            <table class="basic_info_table">
              <caption>用章申请展示</caption>
              <tr>
                <th scope="col"></th>
                <th scope="col"></th>
              </tr>
              <tr>
                <td><span class="red-span">*</span>标题</td>
                <td class="tr-last-child"><span class="right_span">{{form.title}}</span></td>
              </tr>

              <tr>
                <td colspan="2">
                  <hr/>
                </td>
              </tr>

              <tr>
                <td>&nbsp;申请部门</td>
                <td class="tr-last-child"><span class="right_span">{{form.creatorPartyOrgName}}</span></td>
              </tr>

              <tr>
                <td colspan="2">
                  <hr/>
                </td>
              </tr>

              <tr>
                <td>&nbsp;申请人</td>
                <td class="tr-last-child"><span class="right_span">{{form.creatorName}}</span></td>
              </tr>

              <tr>
                <td colspan="2">
                  <hr/>
                </td>
              </tr>

              <tr>
                <td>&nbsp;申请人电话</td>
                <td class="tr-last-child"><span class="right_span">{{form.creatorMobile}}</span></td>
              </tr>

              <tr>
                <td colspan="2">
                  <hr/>
                </td>
              </tr>
              <template v-if="form.useSealType">
                <tr>
                  <td><span class="red-span">*</span>用章类型</td>
                  <td class="tr-last-child">
                    <input type="radio" name="check" disabled v-model="form.useSealType" value="branch"/>支部用章
                    <input type="radio" name="check" disabled
                           v-model="form.useSealType" value="partyCommittee"/>直属党委用章
                  </td>
                </tr>
                <tr>
                  <td colspan="2">
                    <hr/>
                  </td>
                </tr>
              </template>

              <tr>
                <td>&nbsp;用印时间</td>
                <td class="tr-last-child"><span class="right_span">{{form.chapterDate}}</span></td>
              </tr>

              <tr>
                <td colspan="2">
                  <hr/>
                </td>
              </tr>

              <tr>
                <td><span class="red-span">*</span>用印资料</td>
                <td class="tr-last-child"><span class="right_span">{{chapterDocBefore}}</span></td>
              </tr>

              <tr>
                <td colspan="2">
                  <hr/>
                </td>
              </tr>

              <tr>
                <td>&nbsp;份数</td>
                <td class="tr-last-child"><span class="right_span">{{form.docNum}}</span></td>
              </tr>

              <tr>
                <td colspan="2">
                  <hr/>
                </td>
              </tr>

              <tr>
                <td><span class="red-span">*</span>发往单位</td>
                <td class="tr-last-child"><span class="right_span">{{form.sendUnit}}</span></td>
              </tr>

              <tr>
                <td colspan="2">
                  <hr/>
                </td>
              </tr>

              <tr>
                <td><span class="red-span">*</span>内容概要</td>
                <td class="tr-last-child"><span class="right_span">{{form.contentSummary}}</span></td>
              </tr>

              <tr>
                <td colspan="2">
                  <hr/>
                </td>
              </tr>

              <tr>
                <td>&nbsp;用印类别</td>
                <td class="tr-last-child" style="display: flex">
                  <input style="width: 10%; height: 10%" type="checkbox" checked disabled value="">
                  中共中国移动通信集团浙江有限公司直属委员会
                </td>
              </tr>

              <tr>
                <td colspan="2">
                  <hr/>
                </td>
              </tr>

              <!--    附件信息-->
              <tr>
                <td>&nbsp;办理附件</td>
                <td class="tr-last-child" ><em class="iconfont icon-fujian"/></td>
              </tr>

              <tr>
                <td colspan="2">
                  <hr/>
                </td>
              </tr>

              <tr>
                <td class="handAttach" colspan="2">
                  <div class="taskTemplate">
                    <div v-for="item in workApplyData.attachments" :key="item.fileId">
                      <a target="_blank"
                         @click="downloadFile(item.id)"
                         style="color: blue">{{ item.fileName }}</a>
                    </div>
                  </div>
                </td>
              </tr>
            </table>
          </div>

          <!-- 审批意见框 -->
          <template v-if="showOpinion">
            <!-- 如果当前状态是直属党委经办人，或当前状态是拟稿并且用章类型是直属党委用章，则需要选择直属党委负责人 -->
            <div v-if="form.status === 'ZSDWJBR' || (form.status === 'DRAFT' && form.useSealType === 'partyCommittee')">
              <table>
                <caption style="display: none"></caption>
                <tr>
                  <th scope="col">直属党委负责人</th>
                  <th scope="col">
                    <van-radio-group  v-model="form.partyLeaderUid" direction="horizontal">
                      <van-radio v-for="item in zsdwfdrs" :key="item.userId" :name="item.userId">{{ item.userName }}</van-radio>
                    </van-radio-group>
                  </th>
                </tr>
              </table>
            </div>
            <!-- 审批意见-->
            <div class="examInApproxOpinion">
              <h3>审批意见</h3>
            </div>
            <div class="textArea">
              <textarea v-model="form.opinion" placeholder="请输入"></textarea>
            </div>
          </template>

        </van-form>
      </div>
    </div>
    <!--    页脚-->
    <div class="user_seal_apply_footer" >
      <div class="seal_work-bts-cls">
        <button v-if="workProp.showDownloadApproveForm">
          下载审批表
        </button>

        <button  v-if="workProp.showSubmitDraft" @click="useSealApplySubmitChapterDraft">
          提交
        </button>

        <button v-if="workProp.showBackToDraft"  @click="useSealApplyBackToDraft">
          退回至干事
        </button>

        <button v-if="workProp.showReject" @click="useSealApplyRejectRequest">
          退回
        </button>

        <button v-if="workProp.showTransfer" @click="useSealApplyTransfer">
          转交
        </button>

        <button v-if="workProp.showAgree" @click="useSealApplyAgree">
          同意
        </button>

        <button class="op-bt-cls" v-if="workProp.showBack" @click="backBtn()">
          返回
        </button>

      </div>

    </div>

    <!-- 转交功能上拉框 -->
    <van-action-sheet v-model="showTransferSelect" :actions="transferOptions" @select="transferOnSelect" description="请选择转交人"/>

  </div>

</template>

<script>

import API from '@/api/api-chat-list.js'
import {mapState} from "vuex";
import {isEmpty} from "../../../common/util";
import AesGcm from "@/utils/aesgcm";

export default {
  name: "UseSealApplyWorkOrder",
  props: ["workApplyData"],
  components: {},
  computed: {
    ...mapState(['userInfo', 'taskData']),

  },
  data() {

    return {
      showTransferSelect: false, // 是否展示转交人选择框
      transferOptions: [], // 转交人可选列表

      // 弹窗消息
      popUpMsg: '',

      chapterDocOptions: [],

      // 工单状态
      status: '',

      // 按钮状态
      showDownloadApproveForm: false,
      refreshButton: false,
      workProp: {
        showBack: true,
        showSubmitDraft: false,
        showSubmit: false,
        showSave: false,
        showConfirm: false,
        showReport: false,
        showDispatch: false,
        showTransfer: false,
        showReject: false,
        showFinish: false,
        showBackToDraft: false,
        showAgree: false,
      },

      // 表单数据
      form: {
        id: '',
        title: '',
        creatorPartyOrgName: '',
        creatorMobile: '',
        creatorName: '',
        chapterDate: '',
        chapterDoc: '',
        chapterDocOther: '',
        sendUnit: '',
        contentSummary: '',
        opinion: '',
        docNum: 1,
        partyLeaderUid: '',
        partyLeaderName: ''
      },
      chapterDocBefore: '',
      // 直属党委负责人
      zsdwfdrs:[],
      showOpinion: false, // 展示审批意见框

    }
  },

  methods: {

    // 文件下载
    downloadFile(id) {
      MXCommon.download( AesGcm.decrypt(process.env.VUE_APP_API_HOST) + '/api/work/downloadAttachment?attachmentId=' + id);  //下载文件
    },
    /**
     * 返回上一页
     */
    backBtn() {
      this.$store.commit('setWorkOrderType', "workOrderInform");
      this.$router.back();
    },

    // 按钮展示
    showChapterButtonOp(status) {
      switch(status) {
        case 'DRAFT':
          this.workProp.showSubmitDraft=true;
          this.workProp.showSave=true;
          break;
        case 'ZBSJ':
          this.workProp.showAgree=true;
          this.workProp.showReject=true;
          break;
        case 'ZSDWFZR':
          this.workProp.showAgree=true;
          this.workProp.showReject=true;
          this.workProp.showTransfer=true;
          break;
        case 'ZSDWJBR':
          this.workProp.showAgree=true;
          this.workProp.showReject=true;
          this.workProp.showBackToDraft=true;
          break;
        case 'END':
          this.workProp.showDownloadApproveForm=true;
          break;
      }
    },

    /**
     * 展示转交框
     */
    useSealApplyTransfer() {
      this.showTransferSelect = true;
    },

    // 提交
    useSealApplySubmitChapterDraft() {
      this.confirmDialog("确认提交", "submit")
    },

    // 同意
    useSealApplyAgree(){
      if (this.form.status == 'DRAFT') {
        this.$refs['form'].validate((valid) => {
          if (!valid) {
            this.$dialog.alert({
              message:'表单信息校验失败！',
              theme: 'round-button',
            })
            return false;
          }

          this.confirmDialog("确认同意", "submit")
        });
      }

      // 如果当前状态是直属党委经办人，需要提示直属党委负责人必选
      if (this.form.status == 'ZSDWJBR' && !this.form.partyLeaderUid) {
        this.$toast.fail("请选择直属党委负责人");
        return false;
      }
      this.confirmDialog("确认同意", "submit");
    },

    /**
     * 转交人选项选中
     * @param item 转交人对象
     */
    async transferOnSelect(item) {
      this.showTransferSelect = false; // 关闭选人框
      // 校验转交人选择框数据
      if (!item.subname) {
        this.$toast.fail("请选择转交人");
        return false;
      }
      const dialog = await this.$dialog.confirm({
        title: '',
        message: '确认转交该工单，是否继续？',
        confirmButtonColor: 'red',
        theme: 'round-button',
      });
      if (dialog) {
        const form = new FormData();
        form.append('workApplyId', this.form.id);
        form.append('taskId', this.workApplyData.tiid);
        // 如果转交意见为空，则赋值意见为转交
        form.append('opinion', (this.form.opinion ? this.form.opinion : "转交") + "(手机)");
        form.append('transferUserId', item.subname);
        form.append('transferUserName', item.name);
        const res = await API.transferChapterTask(form);
        await this.apiReturnValueProcess(res,"确认转交");
      }
    },

    // 退回
    useSealApplyRejectRequest() {
      // 审批意见填写
      if (!this.form.opinion) {
        this.$dialog.alert({
          title:'确认退回',
          message:'请填写退回意见！',
          theme: 'round-button',
        })
        return false;
      }

      // 弹窗二次确认
      this.confirmDialog("确认退回", "reject")
    },

    // 退回至干事
    useSealApplyBackToDraft(){
      // 审批意见填写
      if (!this.form.opinion) {
        this.$dialog.alert({
          title:'确认退回',
          message:'请填写退回意见！',
          theme: 'round-button',
        })
        return false;
      }
      this.confirmDialog("确认退回至干事", "backToDraft")
    },

    // 通用确认框与请求发送
    async confirmDialog(title, decision) {
      // 二次确认弹窗
      await this.getFormDataAndPopUp(title, decision)

      const dialog = await this.$dialog.confirm({
        title: '',
        message: this.popUpMsg,
        confirmButtonColor: 'red',
        theme: 'round-button',
      });

      if(dialog === "confirm"){
        if(title === '确认提交'){
          await this.doSubmitChapterDraft();
        } else if(title === '确认同意'){
          await this.submitWorkToBackEnd();
        } else if(title === '确认退回'){
          await this.doChapterReject();
        } else if(title === '确认退回至干事'){
          await this.doBackToDraft();
        }
      }

    },

    async doSubmitChapterDraft() {

      const that = this;
      const fd = new FormData();
      fd.append('workApplyInfo', JSON.stringify(that.form));
      if(isEmpty(this.workApplyData)) {
        fd.append('taskId', undefined);
      } else {
        fd.append('taskId', this.workApplyData.tiid);
      }
      const opinion = that.form.opinion ? that.form.opinion + "(手机)" : "请审批(手机)";
      fd.append('opinion', opinion);

      const res = await API.submitChapterDraft(fd);

      await this.apiReturnValueProcess(res, "确认提交")
    },

    async doBackToDraft() {
      const fd = new FormData();
      fd.append('workApplyId', this.form.id);
      fd.append('taskId', this.workApplyData.tiid);
      fd.append('opinion', this.form.opinion + "(手机)");
      const res = await API.backToDraft(fd);

      await this.apiReturnValueProcess(res, "确认退回至干事")
    },

    async doChapterReject() {
      const fd = new FormData();
      fd.append('workApplyId', this.form.id);
      fd.append('taskId', this.workApplyData.tiid);
      fd.append('opinion', this.form.opinion + "(手机)");

      const res = await API.chapterReject(fd);

      await this.apiReturnValueProcess(res,"确认退回");
    },

    async submitWorkToBackEnd() {
      const that = this;
      const fd = new FormData();
      fd.append('workApplyId', this.form.id);
      fd.append('taskId', this.workApplyData.tiid);

      const defaultOpinion = this.form.status === "DRAFT" ? "请审批" : "同意";
      const opinion = that.form.opinion ? that.form.opinion : defaultOpinion;
      fd.append('opinion', opinion + "(手机)");

      if (this.form.status =="ZSDWJBR") {
        fd.append('partyLeaderUid', this.form.partyLeaderUid);
        const fzr = this.zsdwfdrs.filter(item => item.userId === this.form.partyLeaderUid)[0];
        fd.append('partyLeaderName', fzr.userName);
      }

      const res = await API.submitChapterTask(fd);
      await this.apiReturnValueProcess(res,"确认同意")

    },

    async getFormDataAndPopUp(title, decision){
      const fd = new FormData();
      fd.append('workApplyId', this.form.id);
      fd.append('decision', decision);
      /*
        如果当前决策是提交
        并且，下面两个条件满足任意一个，进入if取值直属党委负责人
        1、当前状态是直属党委经办人
        2、当前状态是拟稿，并选择了直属党委用章
       */
      if (decision === "submit"
        && (this.form.status === "ZSDWJBR"
          || (this.form.status === 'DRAFT' && this.form.useSealType === 'partyCommittee'))) {
        // 如果直属党委负责人为空，需要提示必选
        if(!this.form.partyLeaderUid) {
          this.$toast.fail("请选择直属党委负责人");
          return false;
        }
        fd.append('partyLeaderUid', this.form.partyLeaderUid);
        const fzr = this.zsdwfdrs.find(item => item.userId === this.form.partyLeaderUid);
        fd.append('partyLeaderName', fzr.userName);
        this.form.partyLeaderName = fzr.userName;
      }
      fd.append('workApplyInfo', JSON.stringify(this.form));
      const nextNodeInfo = await API.chapterNextNodeInfo(fd);
      if (nextNodeInfo.data.nodeId === "_EOF") {
        this.popUpMsg = "确认将工单送结束吗？";
      } else {
        this.popUpMsg= "确认将工单提交给" + nextNodeInfo.data.userInfo.userName + "（" + nextNodeInfo.data.nodeName + "）吗？";
      }
    },

    validateField(props, cb) {
      props = [].concat(props);
      const fields = this.fields.filter(field => props.indexOf(field.prop) !== -1);
      if (!fields.length) {
        console.warn('[Element Warn]please pass correct props!');
        return;
      }

      fields.forEach(field => {
        field.validate('', cb);
      });
    },

    clearValidate(props = []) {
      const fields = props.length
        ? (typeof props === 'string'
            ? this.fields.filter(field => props === field.prop)
            : this.fields.filter(field => props.indexOf(field.prop) > -1)
        ) : this.fields;
      fields.forEach(field => {
        field.clearValidate();
      });
    },

    async apiReturnValueProcess(res,title){
      if(res.result === '1'){
        const dialog = await this.$dialog.alert({
          title: title,
          message: '操作成功',
          theme: 'round-button',
        })

        if(dialog === "confirm"){
          this.$router.back();
        }
      } else {
        await this.$dialog.alert({
          title: title,
          message: '操作失败',
          theme: 'round-button',
        })
      }
    },

    // 初始数据
    initFormData() {
      this.form = this.workApplyData;
    },
  },

  // 初始化数据
  async created() {
    this.initFormData()

    // 获取用印资料类型
    const chapterDocTypesRes = await API.getChapterDocTypes();
    this.chapterDocOptions = chapterDocTypesRes.data;
    // 匹配被选中的资料类型
    const chapterDocSelect = this.workApplyData.chapterDoc;
    const chapterDocType = this.chapterDocOptions.find(({ value }) => value === chapterDocSelect);
    this.chapterDocBefore = chapterDocType ? chapterDocType.label : null;

    // 判断当前处理人是否是登录用户 如果否不展示流程操作按钮
    const handlerUid = this.workApplyData.handlerUid;
    const userId = this.userInfo.userID;
    if(handlerUid === userId){
      this.showChapterButtonOp(this.workApplyData.status);
      this.showOpinion = true; // 展示审批意见框
    }

    const zsdwfzrRes = await API.getZsdwfzr()
    this.zsdwfdrs = zsdwfzrRes.data;
    // 设置转交人可选数据列表，排除当前登录人
    this.transferOptions = this.zsdwfdrs.filter(item => item.userId !== this.userInfo.userID)
      .map(item => ({
        name: item.userName,
        subname: item.userId
      }));
  },

}
</script>

<style>


.user_seal_apply {
  -webkit-overflow-scrolling: touch;
  position: relative;
  z-index: 100;
  height: 100%;
  overflow-y: auto;
  scroll-behavior: smooth;
  width: 100%;
  margin: 0 auto;
}

.table_div {
  text-align: center;
  background-color: #fff9f9;
  padding: 0.8em 0;
}

/*分割线*/
.user_seal_apply hr {
  border: none;
  border-bottom: 1px solid #DaDaDa;
  height: 1px;
  -webkit-transform: scaleY(0.5);
  -webkit-transform-origin: 0 0;
}


/*主体表格*/
.table_div .basic_info_table{
  width: 100%;
  margin: auto;
  background-color: white;
}

.basic_info_table caption {
  display: none;
}

.basic_info_table tr:first-of-type {
  display: none;
}

/*所有行*/
.user_seal_apply td {
  font-size: 13px;
  padding: 6px 10px;
}

.user_seal_apply .red-span {
  color: red;
}


/*左列*/
.user_seal_apply tr > td:first-child {
  text-align: left;
  width: 30%;
  font-weight: bold;
  font-size: 0.9em;
  vertical-align: middle;
}

/*右列*/
.basic_info_table .tr-last-child {
  text-align: right;
}

/*可拉输入框*/
.user_seal_apply textarea {
  color: #606266;
  border: 0.5px solid red;
  border-radius: 5px;
}

/*审批意见*/
.user_seal_apply .examInApproxOpinion {
  background-color: white;
  padding-bottom: 0.2em;
}

.examInApproxOpinion h3{
  font-size: 1.2em;
  margin: 1em auto;
  padding-top: 1em;
  text-align: center;
}

.user_seal_apply .textArea {
  width: 100%;
  background-color: #fff;
}

.user_seal_apply .textArea textarea{
  display: block;
  resize: vertical;
  padding: 5px 15px;
  line-height: 1.5;
  box-sizing: border-box;
  width: 90%;
  margin: 0 auto;
  font-size: inherit;
  color: #606266;
  background-color: #f7f7f7;
  min-height: 8em;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: border-color .2s cubic-bezier(.645, .045, .355, 1);
}

/*办理附件*/
.user_seal_apply .handAttach{
  text-align: left;
}

/*页脚*/
.user_seal_apply_footer {
  width: 100%;
  background-color: #fff;
  box-sizing: border-box;
  position: fixed;
  bottom: 0;
  z-index: 1000;
  height: 4em;
  box-shadow: 0 0 23px rgb(145 43 43 / 12%);
}

.user_seal_apply_footer  button {
  padding: 0.5em 1em;
  width: 60%;
  margin: 0.7em;
  background-color: #FFFFFF;
  border-radius: 5px;
  border: 1px solid #ED2439;
  color: #ED2439;
}

.user_seal_apply_footer .seal_work-bts-cls {
  display: flex;
  justify-content: center;
}

/*
 转交上拉框隐藏二级名称
 */
.van-action-sheet__subname {
  display:none;
}

</style>
